package cn.shuangbofu.guice.test;

import com.google.inject.AbstractModule;
import com.google.inject.Key;
import com.google.inject.Provides;

import javax.inject.Inject;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.security.SecureRandom;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by shuangbofu on 2020-04-17 11:44
 */
public class GuiceDemo {

    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();
        TestDemo demo = TestDemo.INSTANCE;
        EntityQueue queue = Injectors.getInstance(EntityQueue.class);
//        queue.startRubBall();

//        for (int i = 1; i < 1000; i++) {
//            int value = random.nextInt(10);
//            if (value > 5) {
//                demo.createEntity(String.valueOf(i));
//            }
//
//            if (i % 10 == 0) {
//                demo.releaseEntity(random.nextInt(5));
//            }
//            try {
//                Thread.sleep(1000);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            if (i % 100 == 0) {
//                System.out.println("----------------------");
//                Map<Entity, Pair<Integer, Boolean>> total = queue.getTotal();
//                for (Entity entity : total.keySet()) {
//                    Pair<Integer, Boolean> pair = total.get(entity);
//                    System.out.println(entity.getName() + ":" + pair.getFirst() + ":" + pair.getSecond());
//                }
//                System.out.println("----------------------");
//            }
//        }
    }

    @Qualifier
    @Retention(RUNTIME)
    @interface Message {
    }

    @Qualifier
    @Retention(RUNTIME)
    @interface Count {
    }

    /**
     * Guice module that provides bindings for message and count used in
     * {@link Greeter}.
     */
    static class DemoModule extends AbstractModule {
        @Provides
        @Count
        static Integer provideCount() {
            return 3;
        }

        @Override
        protected void configure() {
            bind(Key.get(String.class, Message.class)).toInstance("hello world");
        }
    }

    static class Greeter {
        private final String message;
        private final int count;

        // Greeter declares that it needs a string message and an integer
        // representing the number of time the message to be printed.
        // The @Inject annotation marks this constructor as eligible to be used by
        // Guice.
        @Inject
        Greeter(@Message String message, @Count int count) {
            this.message = message;
            this.count = count;
        }

        void sayHello() {
            for (int i = 0; i < count; i++) {
                System.out.println(message);
            }
        }
    }
}
